<?php


// // 设置允许的来源，这里假设允许来自 http://1.13.198.191:8081 的请求
// header("Access-Control-Allow-Origin: http://1.13.198.191:8081");
header("Access-Control-Allow-Origin: http://localhost:9528");
// 允许携带凭证
header("Access-Control-Allow-Credentials: true");
// 允许的HTTP方法
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// 允许的请求头
header("Access-Control-Allow-Headers: Content-Type");

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

session_start();

// 读取请求体并解析 JSON 数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_encode(['Code' => 400, 'Msg' => '无效的 JSON 数据'], JSON_UNESCAPED_UNICODE);
    exit();
}

// 获取用户名和密码
$uname = isset($data['username']) ? $data['username'] : null;
$passwd = isset($data['passwd']) ? $data['passwd'] : null;
// echo $uname;
// echo $passwd;
// 启动 session

if ($uname && $passwd) {
    require_once "./conn.php";
    $sql = "SELECT * FROM users WHERE uname=? AND password=? AND isadmin='1'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $uname, $passwd);
    $stmt->execute();

    if ($rs = $stmt->get_result()) {
        if ($row = $rs->fetch_row()) {
            $_SESSION['username'] = $uname;
            $_SESSION['isadmin'] = 1;
            $_SESSION['userid'] = $row[0];

            // 登录成功，返回 JSON 格式
            echo json_encode(['Code' => 200, 'Msg' => '登录成功', 'Ret' => "True", 'Data' => [
                'username' => $_SESSION['username'],
                'isadmin' => $_SESSION['isadmin'],
                'userid' => $_SESSION['userid']
            ]], JSON_UNESCAPED_UNICODE);
            exit();
        } else {
            // 账号不存在或者密码错误
            echo json_encode(['Code' => 0, 'Msg' => '账号不存在或者密码错误', 'Ret' => "False"], JSON_UNESCAPED_UNICODE);
            exit();
        }
    } else {
        // 登录失败
        echo json_encode(['Code' => 0, 'Msg' => '登录失败', 'Ret' => "False"], JSON_UNESCAPED_UNICODE);
        exit();
    }
} else if (!$uname) {
    // 页面没有登录
    echo json_encode(['Code' => 0, 'Msg' => '请输入账号', 'Ret' => "False"], JSON_UNESCAPED_UNICODE);
    exit();
} else if (!$passwd) {
    echo json_encode(['Code' => 0, 'Msg' => '请输入密码', 'Ret' => "False"], JSON_UNESCAPED_UNICODE);
    exit();
}
